import request from '@/utils/request.js'
import { removeTokenInfo, setTokenInfo } from '@/utils/storage'

// 发送验证码的action
export const sendCode = (mobile) => {
  return async () => {
    await request({
      url: `/sms/codes/${mobile}`,
      method: 'GET',
    })
  }
}

export const saveToken = (payload) => ({ type: 'login/token', payload })

// 登录的action
export const login = (data) => {
  return async (dispatch) => {
    const res = await request({
      url: `/authorizations`,
      method: 'POST',
      data,
    })
    dispatch(saveToken(res.data))
    // 把token保存到本地
    setTokenInfo(res.data)
  }
}

// 退出登录
export const logout = (data) => {
  return (dispatch) => {
    // 移除本地的token
    removeTokenInfo()
    dispatch({
      type: 'login/logout',
    })
  }
}
